package com.uzai.console.service.fd.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.dto.base.BizLog;
import com.uzai.common.enums.LogBizTypeEnum;
import com.uzai.common.enums.MessageTypeEnum;
import com.uzai.common.enums.PlatformTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.fd.fdgoodspara.FdGoodsParaDto;
import com.uzai.console.dto.fd.fdgoodspara.FdGoodsParaPreviewDto;
import com.uzai.console.dto.fd.fdtemplate.FdTemplateDto;
import com.uzai.console.dto.fd.fdtemplate.FdTemplateIdDto;
import com.uzai.console.dto.fd.fdtemplate.FdTemplateQuery;
import com.uzai.console.dto.feign.turnlink.SimpleTurnLinkDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.entity.*;
import com.uzai.console.enums.FdGoodsParaEnum;
import com.uzai.console.jsonvo.fd.fdtemplate.FdTemplateData;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.fd.FdTemplateService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiTurnlinkFeignService;
import com.uzai.console.vo.fd.fdtemplate.FdTemplateVo;
import com.uzai.console.vo.feign.turnlink.SimpleTurnlinkVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 发单模板
 *
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class FdTemplateServiceImpl implements FdTemplateService {

    Logger logger = LoggerFactory.getLogger(FdTemplateServiceImpl.class);

    @Autowired
    private FdTemplateMapper fdTemplateMapper;
    @Autowired
    private FdGoodsParaMapper fdGoodsParaMapper;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private FdDevicePlanMapper fdDevicePlanMapper;
    @Autowired
    private UzaiTurnlinkFeignService uzaiTurnlinkFeignService;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private FdDevicePlanGroupMapper fdDevicePlanGroupMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;

    /**
     * 查询发单模板列表
     *
     * @param fdTemplateQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<FdTemplateVo> findFdTemplateList(FdTemplateQuery fdTemplateQuery) {
        //新建返回到页面的LIST对象
        List<FdTemplateVo> fdTemplatePageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<FdTemplate> page = new Page<>();
        fdTemplateQuery.convert(page);
        ArrayList<FdTemplate> fdTemplateList = fdTemplateMapper.findByList(page, fdTemplateQuery);
        if (fdTemplateList != null && fdTemplateList.size() > 0) {
            for (FdTemplate fdTemplate : fdTemplateList) {
                FdTemplateVo fdTemplateVo = new FdTemplateVo();
                BeanUtils.copyProperties(fdTemplate, fdTemplateVo);
                if (StringUtils.isNotBlank(fdTemplate.getData())) {
                    try {
                        List<FdTemplateData> fdTemplateDataList = JSONObject.parseArray(fdTemplate.getData(), FdTemplateData.class);
                        fdTemplateVo.setFdTemplateDataList(fdTemplateDataList);
                    } catch (Exception e) {

                    }
                }
                fdTemplatePageVoList.add(fdTemplateVo);
            }
        }

        //返回到页面分页对象
        Page<FdTemplateVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(fdTemplatePageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询发单模板详情
     *
     * @param fdTemplateIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public FdTemplateVo findFdTemplate(FdTemplateIdDto fdTemplateIdDto) {
        if (fdTemplateIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        FdTemplate fdTemplate = fdTemplateMapper.selectById(fdTemplateIdDto.getId(), fdTemplateIdDto.getMerId());

        if (fdTemplate == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该发单模板不存在");
        }

        FdTemplateVo fdTemplateVo = new FdTemplateVo();
        BeanUtils.copyProperties(fdTemplate, fdTemplateVo);

        if (StringUtils.isNotBlank(fdTemplate.getData())) {
            try {
                List<FdTemplateData> fdTemplateDataList = JSONObject.parseArray(fdTemplate.getData(), FdTemplateData.class);
                fdTemplateVo.setFdTemplateDataList(fdTemplateDataList);
            } catch (Exception e) {

            }
        }
        return fdTemplateVo;
    }

    /**
     * 添加发单模板
     *
     * @param fdTemplateDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void addFdTemplate(FdTemplateDto fdTemplateDto) {

        if (StringUtils.isBlank(fdTemplateDto.getName())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入方案名称");
        }

        //发单内容
        List<FdTemplateData> fdTemplateDataList = fdTemplateDto.getFdTemplateDataList();
        if (fdTemplateDataList == null || fdTemplateDataList.size() == 0) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请设置发单内容");
        }

        //循环设置内容，如果包含
        for (FdTemplateData fdTemplateData : fdTemplateDataList) {

            if (fdTemplateData.getMsgType() == null) {
                throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请设置消息内容类型");
            }

            if (fdTemplateData.getMsgType().intValue() == MessageTypeEnum.MT_TEXT.getValue()) { //文本消息
                if (StringUtils.isNotBlank(fdTemplateData.getContent())) {
                    //需要判断是否含有变量，如果含有变量，则需要判断该变量是否存在，不存在，则提示错误
                    //查询淘口令变量[淘口令+ID]
                    String regex_pwd = FdGoodsParaEnum.PWD.getRegex();
                    List<String> pwdList = Tools.findStrMatchListByRegex(fdTemplateData.getContent(), regex_pwd);
                    if (pwdList != null && pwdList.size() > 0) {
                        for (String pwdStr : pwdList) {
                            //去除前后[]符号
                            String pwdStr_new = pwdStr.substring(1, pwdStr.length() - 1);
                            String[] goodsParaArr = pwdStr_new.split("\\+");
                            String goodsParaId = goodsParaArr[1];
                            FdGoodsPara fdGoodsPara = fdGoodsParaMapper.selectById(Long.valueOf(goodsParaId), fdTemplateDto.getMerId());
                            if (fdGoodsPara == null) {
                                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "淘口令变量参数中商品信息不存在");
                            }
                        }
                    }
                    //查询短链接变量[短链接+ID]
                    String regex_shortLink = FdGoodsParaEnum.SHORTLINK.getRegex();
                    List<String> shortLinkList = Tools.findStrMatchListByRegex(fdTemplateData.getContent(), regex_shortLink);
                    if (shortLinkList != null && shortLinkList.size() > 0) {
                        for (String shortLinkStr : shortLinkList) {
                            //去除前后[]符号
                            String shortLinkStr_new = shortLinkStr.substring(1, shortLinkStr.length() - 1);
                            String[] goodsParaArr = shortLinkStr_new.split("\\+");
                            String goodsParaId = goodsParaArr[1];
                            FdGoodsPara fdGoodsPara = fdGoodsParaMapper.selectById(Long.valueOf(goodsParaId), fdTemplateDto.getMerId());
                            if (fdGoodsPara == null) {
                                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "短链接变量参数中商品信息不存在");
                            }
                        }
                    }
                }
            }
        }

        //先添加模板
        Integer now = DateUtil.getNowTime();

        FdTemplate fdTemplate = new FdTemplate();
        fdTemplate.setId(IdWorker.getId());
        fdTemplate.setMerId(fdTemplateDto.getMerId());
        fdTemplate.setName(fdTemplateDto.getName());
        fdTemplate.setData(Tools.getStrEmpty(JSONObject.toJSONString(fdTemplateDto.getFdTemplateDataList())));
        fdTemplate.setCreateTime(now);
        fdTemplate.setUpdateTime(now);
        fdTemplateMapper.insertSelective(fdTemplate);

    }

    /**
     * 修改发单模板
     *
     * @param fdTemplateDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void updateFdTemplate(FdTemplateDto fdTemplateDto) {

        if (fdTemplateDto.getId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入方案id");
        }

        if (StringUtils.isBlank(fdTemplateDto.getName())) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入方案名称");
        }

        //发单内容
        List<FdTemplateData> fdTemplateDataList = fdTemplateDto.getFdTemplateDataList();
        if (fdTemplateDataList == null || fdTemplateDataList.size() == 0) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请设置发单内容");
        }

        //循环设置内容，如果包含
        for (FdTemplateData fdTemplateData : fdTemplateDataList) {

            if (fdTemplateData.getMsgType() == null) {
                throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请设置消息内容类型");
            }

            if (fdTemplateData.getMsgType().intValue() == MessageTypeEnum.MT_TEXT.getValue()) { //文本消息
                if (StringUtils.isNotBlank(fdTemplateData.getContent())) {
                    //需要判断是否含有变量，如果含有变量，则需要判断该变量是否存在，不存在，则提示错误
                    //查询淘口令变量[淘口令+ID]
                    String regex_pwd = FdGoodsParaEnum.PWD.getRegex();
                    List<String> pwdList = Tools.findStrMatchListByRegex(fdTemplateData.getContent(), regex_pwd);
                    if (pwdList != null && pwdList.size() > 0) {
                        for (String pwdStr : pwdList) {
                            //去除前后[]符号
                            String pwdStr_new = pwdStr.substring(1, pwdStr.length() - 1);
                            String[] goodsParaArr = pwdStr_new.split("\\+");
                            String goodsParaId = goodsParaArr[1];
                            FdGoodsPara fdGoodsPara = fdGoodsParaMapper.selectById(Long.valueOf(goodsParaId), fdTemplateDto.getMerId());
                            if (fdGoodsPara == null) {
                                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "淘口令变量参数中商品信息不存在");
                            }
                        }
                    }

                    //查询短链接变量[短链接+ID]
                    String regex_shortLink = FdGoodsParaEnum.SHORTLINK.getRegex();
                    List<String> shortLinkList = Tools.findStrMatchListByRegex(fdTemplateData.getContent(), regex_shortLink);
                    if (shortLinkList != null && shortLinkList.size() > 0) {
                        for (String shortLinkStr : shortLinkList) {
                            //去除前后[]符号
                            String shortLinkStr_new = shortLinkStr.substring(1, shortLinkStr.length() - 1);
                            String[] goodsParaArr = shortLinkStr_new.split("\\+");
                            String goodsParaId = goodsParaArr[1];
                            FdGoodsPara fdGoodsPara = fdGoodsParaMapper.selectById(Long.valueOf(goodsParaId), fdTemplateDto.getMerId());
                            if (fdGoodsPara == null) {
                                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "短链接变量参数中商品信息不存在");
                            }
                        }
                    }
                }
            }
        }

        FdTemplate fdTemplate = fdTemplateMapper.selectById(fdTemplateDto.getId(), fdTemplateDto.getMerId());
        if (fdTemplate == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该模板不存在");
        }

        Integer now = DateUtil.getNowTime();
        //修改发单模板
        fdTemplate.setName(fdTemplateDto.getName());
        fdTemplate.setData(Tools.getStrEmpty(JSONObject.toJSONString(fdTemplateDto.getFdTemplateDataList())));
        fdTemplate.setUpdateTime(now);
        fdTemplateMapper.updateByIdSelective(fdTemplate);

    }

    /**
     * 删除
     *
     * @param fdTemplateIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void deleteFdTemplate(FdTemplateIdDto fdTemplateIdDto) {
        if (fdTemplateIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        // TODO: 2022/3/8  查询该模板是否已经给发单占用了
        //删除模板
        fdTemplateMapper.deleteById(fdTemplateIdDto.getId(), fdTemplateIdDto.getMerId());
    }

    /**
     * 查询发单模板下拉列表
     *
     * @param query
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public List<FdTemplateVo> findFdTemplateListByAll(FdTemplateQuery query) {
        List<FdTemplateVo> fdTemplateVoList = new ArrayList<>();
        List<FdTemplate> fdTemplateList = fdTemplateMapper.findByList(query);
        if (fdTemplateList != null && fdTemplateList.size() > 0) {
            for (FdTemplate fdTemplate : fdTemplateList) {
                FdTemplateVo fdTemplateVo = new FdTemplateVo();
                BeanUtils.copyProperties(fdTemplate, fdTemplateVo);
                fdTemplateVoList.add(fdTemplateVo);
            }
        }
        return fdTemplateVoList;
    }

    /**
     * 添加商品变量
     *
     * @param fdGoodsParaDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public String addFdGoodsPara(FdGoodsParaDto fdGoodsParaDto) {

        String returnStr = "";

        if (StringUtils.isBlank(fdGoodsParaDto.getItemId())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品id不能为空");
        }
        Long id = IdWorker.getId();
        int now = DateUtil.getNowTime();
        FdGoodsPara fdGoodsPara = new FdGoodsPara();
        fdGoodsPara.setId(id);
        fdGoodsPara.setMerId(fdGoodsParaDto.getMerId());
        fdGoodsPara.setCouponId(fdGoodsParaDto.getCouponId());
        fdGoodsPara.setPlatform(fdGoodsParaDto.getPlatform());
        fdGoodsPara.setItemId(fdGoodsParaDto.getItemId());
        fdGoodsPara.setParaType(fdGoodsParaDto.getParaType());
        fdGoodsPara.setCreateTime(now);
        fdGoodsPara.setUpdateTime(now);
        fdGoodsParaMapper.insertSelective(fdGoodsPara);
        FdGoodsParaEnum fdGoodsParaEnum = FdGoodsParaEnum.getById(fdGoodsParaDto.getParaType());
        if (fdGoodsParaEnum != null) {
            returnStr = String.format(fdGoodsParaEnum.getPara(), id);
        }
        return returnStr;
    }

    /**
     * 预览商品信息预览商品信息
     *
     * @param fdGoodsParaPreviewDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public String previewFdGoodsPara(FdGoodsParaPreviewDto fdGoodsParaPreviewDto) {

        String content = fdGoodsParaPreviewDto.getContent();
        if (StringUtils.isBlank(content)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "商品信息不能为空");
        }

        String content_new = Tools.getStr(content);

        if (fdGoodsParaPreviewDto.getFdDevicePlanId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请上传设备方案id参数");
        }

        FdDevicePlan fdDevicePlan = fdDevicePlanMapper.selectById(fdGoodsParaPreviewDto.getFdDevicePlanId(), fdGoodsParaPreviewDto.getMerId());
        if (fdDevicePlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该设备方案不存在");
        }

        //查询默认第一个机器人
        DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
        deviceWechatInfoQuery.setMerId(fdGoodsParaPreviewDto.getMerId());
        List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
        if (deviceWechatInfoList == null || deviceWechatInfoList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商未购买机器人，不能转链商品");
        }
        //默认取第一个
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoList.get(0);

        //需要判断是否含有变量，如果含有变量，则需要判断该变量是否存在，存在，则转链
        //查询淘口令变量[淘口令+ID]
        String regex_pwd = FdGoodsParaEnum.PWD.getRegex();
        List<String> pwdList = Tools.findStrMatchListByRegex(content, regex_pwd);
        if (pwdList != null && pwdList.size() > 0) {
            for (String pwdStr : pwdList) {
                //去除前后[]符号
                String pwdStr_new = pwdStr.substring(1, pwdStr.length() - 1);
                String[] goodsParaArr = pwdStr_new.split("\\+");
                String goodsParaId = goodsParaArr[1];
                FdGoodsPara fdGoodsPara = fdGoodsParaMapper.selectById(Long.valueOf(goodsParaId), fdGoodsParaPreviewDto.getMerId());
                if (fdGoodsPara != null) {
                    //转链
                    SimpleTurnlinkVo goodInfo_pwd = getGoodInfo(fdGoodsPara, fdDevicePlan, deviceWechatInfo);
                    if (goodInfo_pwd != null && StringUtils.isNotBlank(goodInfo_pwd.getPurePwd())) {
                        //淘口令
                        String pwd = goodInfo_pwd.getBuyPwd();
                        //淘口令前缀
                        String pwdpres = fdDevicePlan.getPwdpres();
                        //淘口令后缀
                        String pwdsufs = fdDevicePlan.getPwdsufs();
                        //如果前缀和后缀都有，则取裸淘口令
                        if (StringUtils.isNotBlank(pwdpres) && StringUtils.isNotBlank(pwdsufs)) {
                            pwd = goodInfo_pwd.getPurePwd(); //裸淘口令
                            //根据设备方案配置的前缀和后缀拼凑淘口令
                            if (StringUtils.isNotBlank(pwdpres)) {
                                List<String> pwdpreList = JSONObject.parseArray(pwdpres, String.class);
                                if (pwdpreList != null && pwdpreList.size() > 0) {
                                    String pwdpre_random = pwdpreList.get((int) (Math.random() * pwdpreList.size()));
                                    pwd = pwdpre_random + pwd;
                                }
                            }
                            if (StringUtils.isNotBlank(pwdsufs)) {
                                List<String> pwdsufList = JSONObject.parseArray(pwdsufs, String.class);
                                if (pwdsufList != null && pwdsufList.size() > 0) {
                                    String pwdsuf_random = pwdsufList.get((int) (Math.random() * pwdsufList.size()));
                                    pwd = pwd + pwdsuf_random;
                                }
                            }
                        }
                        //替换淘口令
                        content_new = content.replace(pwdStr, pwd);
                    }
                }
            }
        }

        //查询短链接变量[短链接+ID]
        String regex_shortLink = FdGoodsParaEnum.SHORTLINK.getRegex();
        List<String> shortLinkList = Tools.findStrMatchListByRegex(content, regex_shortLink);
        if (shortLinkList != null && shortLinkList.size() > 0) {
            for (String shortLinkStr : shortLinkList) {
                //去除前后[]符号
                String shortLinkStr_new = shortLinkStr.substring(1, shortLinkStr.length() - 1);
                String[] goodsParaArr = shortLinkStr_new.split("\\+");
                String goodsParaId = goodsParaArr[1];
                FdGoodsPara fdGoodsPara = fdGoodsParaMapper.selectById(Long.valueOf(goodsParaId), fdGoodsParaPreviewDto.getMerId());
                if (fdGoodsPara != null) {
                    //转链
                    SimpleTurnlinkVo goodInfo_url = getGoodInfo(fdGoodsPara, fdDevicePlan, deviceWechatInfo);
                    if (goodInfo_url != null && StringUtils.isNotBlank(goodInfo_url.getBuyUrl())) {
                        content_new = content.replace(shortLinkStr, goodInfo_url.getBuyUrl());
                    }
                }
            }
        }

        //查询抖音口令变量[抖音口令+ID]
        String regex_tiktokPwd = FdGoodsParaEnum.TIKTOK_PWD.getRegex();
        List<String> tiktokPwdList = Tools.findStrMatchListByRegex(content, regex_tiktokPwd);
        if (tiktokPwdList != null && tiktokPwdList.size() > 0) {
            for (String tiktokPwdStr : tiktokPwdList) {
                //去除前后[]符号
                String tiktokPwdStr_new = tiktokPwdStr.substring(1, tiktokPwdStr.length() - 1);
                String[] goodsParaArr = tiktokPwdStr_new.split("\\+");
                String goodsParaId = goodsParaArr[1];
                FdGoodsPara fdGoodsPara = fdGoodsParaMapper.selectById(Long.valueOf(goodsParaId), fdGoodsParaPreviewDto.getMerId());
                if (fdGoodsPara != null) {
                    //转链
                    SimpleTurnlinkVo goodInfo_pwd = getGoodInfo(fdGoodsPara, fdDevicePlan, deviceWechatInfo);
                    if (goodInfo_pwd != null && StringUtils.isNotBlank(goodInfo_pwd.getBuyPwd())) {
                        content_new = content.replace(tiktokPwdStr, goodInfo_pwd.getBuyPwd());
                    }
                }
            }
        }

        return content_new;
    }

    /**
     * 获取商品信息
     *
     * @param deviceWechatInfo
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public SimpleTurnlinkVo getGoodInfo(FdGoodsPara fdGoodsPara, FdDevicePlan fdDevicePlan, DeviceWechatInfo deviceWechatInfo) {

        SimpleTurnlinkVo simpleTurnlinkVo = new SimpleTurnlinkVo();
        if (fdGoodsPara.getPlatform() == null) {
            logger.info("请选择平台");
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择平台");
        }

        Long tbTokenId = null;
        String tbPid = "";
        String tbRid = "";
        Long jdTokenId = null;
        Long pddTokenId = null;
        Long vphTokenId = null;
        Integer pddTokenType = null;
        Integer dyTokenType = null;
        Long dyTokenId = null;
        //中间页参数
        Integer middlePageType = null;
        String middlePageUrl = "";
        //机器人身上的配置方案
        ConfigPlan configPlan = null;
        //获取配置方案关联的第一个群信息
        FdDevicePlanGroup fdDevicePlanGroup_first = null;

        //查询该配置方案关联的群信息
        List<FdDevicePlanGroup> fdDevicePlanGroupList = fdDevicePlanGroupMapper.findByListByFdDevicePlanId(fdDevicePlan.getId(), fdDevicePlan.getMerId());
        if (fdDevicePlanGroupList == null || fdDevicePlanGroupList.size() == 0) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置任何群信息");
        }

        ///获取配置方案关联的第一个群信息
        fdDevicePlanGroup_first = fdDevicePlanGroupList.get(0);
        //获取第一个群关联的机器人信息
        Device device = deviceService.findDeviceInfoByDeviceUniqueId(fdDevicePlanGroup_first.getGroupSendDeviceUniqueId(), fdDevicePlanGroup_first.getDeviceType(), fdDevicePlanGroup_first.getMerId());
        if (device == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "第一个群配置的机器人不存在");
        }

        //淘宝商品
        if (fdGoodsPara.getPlatform().intValue() == 0) {

            //1-从配置方案的群相关设置中获取联盟
            tbTokenId = fdDevicePlanGroup_first.getTbTokenId();
            tbPid = fdDevicePlanGroup_first.getTbPid();
            tbRid = fdDevicePlanGroup_first.getTbRid();
            middlePageType = fdDevicePlanGroup_first.getMiddlePageType();
            middlePageUrl = fdDevicePlanGroup_first.getMiddlePageUrl();

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if (fdDevicePlan.getTokenSet() != null && fdDevicePlan.getTokenSet().intValue() == 1) { //自己设置联盟
                if (tbTokenId == null) {
                    //从配置方案中获取
                    tbTokenId = fdDevicePlan.getTbTokenId();
                }
                if (StringUtils.isBlank(tbPid)) {
                    tbPid = fdDevicePlan.getTbPid();
                }
                if (StringUtils.isBlank(tbRid)) {
                    tbRid = fdDevicePlan.getTbRid();
                }

                if (middlePageType == null) {
                    middlePageType = fdDevicePlan.getMiddlePageType();
                }

                if (StringUtils.isBlank(middlePageUrl)) {
                    middlePageUrl = fdDevicePlan.getMiddlePageUrl();
                }
            }

            //3-如果联盟信息还为空，则从群管理配置的机器身上获取
            if (tbTokenId == null) {
                if (configPlan == null) {
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if (configPlan != null) {
                    //淘宝token,淘宝商品不从配置方案中获取，淘宝采用导购联盟
                    if (false) {
                        JSONObject jsonObject_tb = JSONObject.parseObject(configPlan.getTbAccountId());
                        if (jsonObject_tb != null) {
                            JSONArray jsonArray = jsonObject_tb.getJSONArray("tokens");
                            if (jsonArray != null && jsonArray.size() > 0) {
                                JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                                String tokenIds = jsonObject.getString("tokenIds");
                                List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                                if (tokenList != null && tokenList.size() > 0) {
                                    tbTokenId = tokenList.get(0);
                                    TbToken tbToken = tbTokenMapper.selectById(tbTokenId, deviceWechatInfo.getMerId());
                                    if (tbToken != null) {
                                        tbPid = tbToken.getDefPid();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //中间页还为空，则从群管理配置的机器人身上获取
            if (middlePageType == null || StringUtils.isBlank(middlePageUrl)) {
                if (configPlan == null) {
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if (configPlan != null) {
                    //淘宝插件id
                    Long tbId = configPlan.getTbId();
                    SysPlugin sysPlugin = sysPluginMapper.selectById(tbId, configPlan.getMerId());
                    if (sysPlugin != null) {
                        //淘宝token
                        JSONObject jsonObject_tb = JSONObject.parseObject(sysPlugin.getData());
                        if (jsonObject_tb != null) {
                            middlePageType = jsonObject_tb.getInteger("middle_page_type");
                            middlePageUrl = jsonObject_tb.getString("middle_page_url");
                        }
                    }
                }
            }
        } else if (fdGoodsPara.getPlatform().intValue() == 1) {//京东
            //1-从配置方案的群相关设置中获取联盟
            jdTokenId = fdDevicePlanGroup_first.getJdTokenId();

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if (jdTokenId == null) {
                //从配置方案中获取
                jdTokenId = fdDevicePlan.getJdTokenId();
            }

            //3-最后从配置的机器人当中获取
            if (jdTokenId == null) {
                if (configPlan == null) {
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if (configPlan != null) {
                    //京东token
                    JSONObject jsonObject_jd = JSONObject.parseObject(configPlan.getJdAccountId());
                    if (jsonObject_jd != null) {
                        JSONArray jsonArray = jsonObject_jd.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                jdTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }
        } else if (fdGoodsPara.getPlatform().intValue() == 2) { //拼多多
            //1-从配置方案的群相关设置中获取联盟
            pddTokenType = fdDevicePlanGroup_first.getPddTokenType();
            if (pddTokenType != null && pddTokenType.intValue() == 1) {
                pddTokenId = fdDevicePlanGroup_first.getPddTlbTokenId();
            } else {
                pddTokenId = fdDevicePlanGroup_first.getPddTokenId();
            }

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if (pddTokenId == null) {
                //从配置方案中获取
                pddTokenType = fdDevicePlan.getPddTokenType();
                if (pddTokenType != null && pddTokenType.intValue() == 1) {
                    pddTokenId = fdDevicePlan.getPddTlbTokenId();
                } else {
                    pddTokenId = fdDevicePlan.getPddTokenId();
                }
            }

            //3-最后从机器人中的配置方案获取
            if (pddTokenId == null) {
                if (configPlan == null) {
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if (configPlan != null) {
                    //拼多多token
                    JSONObject jsonObject_pdd = null;
                    pddTokenType = configPlan.getPddAccountType();
                    if (pddTokenType != null && pddTokenType.intValue() == 1) { //拼多多推老板共享联盟
                        jsonObject_pdd = JSONObject.parseObject(configPlan.getTlbPddAccountId());
                    } else { //拼多多联盟
                        jsonObject_pdd = JSONObject.parseObject(configPlan.getPddAccountId());
                    }
                    if (jsonObject_pdd != null) {
                        JSONArray jsonArray = jsonObject_pdd.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                pddTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }
        } else if (fdGoodsPara.getPlatform().intValue() == 3) { //唯品会
            //1-从配置方案的群相关设置中获取联盟
            vphTokenId = fdDevicePlanGroup_first.getVphTokenId();

            //2-如果群相关设置中没有设置，则从配置方案中获取
            if (vphTokenId == null) {
                //从配置方案中获取
                vphTokenId = fdDevicePlan.getVphTokenId();
            }

            //3-最后从机器人中配置方案中获取
            if (vphTokenId == null) {
                if (configPlan == null) {
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if (configPlan != null) {
                    //唯品会token
                    JSONObject jsonObject_vph = JSONObject.parseObject(configPlan.getVphAccountId());
                    if (jsonObject_vph != null) {
                        JSONArray jsonArray = jsonObject_vph.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                vphTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }
        } else if (fdGoodsPara.getPlatform().intValue() == 4) { //抖音
            //1-从配置方案的群相关设置中获取联盟
            dyTokenType = fdDevicePlanGroup_first.getDyTokenType();
            if (dyTokenType != null && dyTokenType.intValue() == 1) {
                dyTokenId = fdDevicePlanGroup_first.getDyTlbTokenId();
            } else {
                dyTokenId = fdDevicePlanGroup_first.getDyTokenId();
            }
            middlePageType = fdDevicePlanGroup_first.getMiddlePageType();
            middlePageUrl = fdDevicePlanGroup_first.getMiddlePageUrl();


            //2-如果群相关设置中没有设置，则从配置方案中获取
            if (dyTokenId == null) {
                //从配置方案中获取
                dyTokenType = fdDevicePlan.getDyTokenType();
                if (dyTokenType != null && dyTokenType.intValue() == 1) {
                    dyTokenId = fdDevicePlan.getDyTlbTokenId();
                } else {
                    dyTokenId = fdDevicePlan.getDyTokenId();
                }
            }
            if (middlePageType == null) {
                middlePageType = fdDevicePlan.getMiddlePageType();
            }

            if (StringUtils.isBlank(middlePageUrl)) {
                middlePageUrl = fdDevicePlan.getMiddlePageUrl();
            }


            //3-最后从机器人中的配置方案获取
            if (dyTokenId == null) {
                if (configPlan == null) {
                    configPlan = configPlanMapper.selectById(device.getConfigId(), device.getMerId());
                }
                if (configPlan != null) {
                    //抖音token
                    JSONObject jsonObject_dy = null;
                    dyTokenType = configPlan.getDyAccountType();
                    if (dyTokenType != null && dyTokenType.intValue() == 1) { //抖音推老板共享联盟
                        jsonObject_dy = JSONObject.parseObject(configPlan.getTlbDyAccountId());
                    } else { //拼多多联盟
                        jsonObject_dy = JSONObject.parseObject(configPlan.getDyAccountId());
                    }
                    if (jsonObject_dy != null) {
                        JSONArray jsonArray = jsonObject_dy.getJSONArray("tokens");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
                            String tokenIds = jsonObject.getString("tokenIds");
                            List<Long> tokenList = JSONObject.parseArray(tokenIds, Long.class);
                            if (tokenList != null && tokenList.size() > 0) {
                                dyTokenId = tokenList.get(0);
                            }
                        }
                    }
                }
            }
        }

        if (StringUtils.isBlank(fdGoodsPara.getItemId())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入商品链接/id");
        }

        SimpleTurnLinkDto simpleTurnLinkDto = new SimpleTurnLinkDto();
        simpleTurnLinkDto.setMerId(deviceWechatInfo.getMerId());
        simpleTurnLinkDto.setDeviceUniqueId(device.getId());
        simpleTurnLinkDto.setDeviceType(device.getRecvmsgType());
        simpleTurnLinkDto.setCouponId(fdGoodsPara.getCouponId());

        //根据商品参数类型来做区分，如果是淘口令参数，则只需转链，如果是短链接参数，则还需转短链接
        if (fdGoodsPara.getPlatform().intValue() == PlatformTypeEnum.PT_TAOBAO_VALUE || fdGoodsPara.getPlatform().intValue() == 4) {//只有淘宝和抖音 才有中间页
            //根据商品参数类型来做区分，如果是淘口令参数，则只需转链，如果是短链接参数，则还需转短链接
            if (Tools.getInteger(fdGoodsPara.getParaType()).intValue() == 1) { //短链接
                //该群内自定义配置、配置方案的配置、机器人身上配置，都没有找到中间页配置信息，故返回异常
                if (middlePageType == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置中间页域名信息");
                }
                simpleTurnLinkDto.setGenerateShortUrl(1);
                if (middlePageType.intValue() == 0 || middlePageType.intValue() == 1) {//官方域名或自有域名
                    try {
                        simpleTurnLinkDto.setMiddlePageDomainId(Long.valueOf(middlePageUrl));
                    } catch (Exception e) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案配置的中间页域名信息有误");
                    }
                } else {//自定义链接
                    simpleTurnLinkDto.setMiddlePageUrl(middlePageUrl);
                }
            }
        }

        UzaiRespVo<SimpleTurnlinkVo> uzaiRespVo = null;
        if (PlatformTypeEnum.PT_TAOBAO.getId().intValue() == fdGoodsPara.getPlatform().intValue()) { //淘宝
            if (tbTokenId == null) { //发单设备方案未配置淘宝联盟id
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置淘宝联盟");
            } else {
                //判断输入得是商品id还是商品链接
                if (fdGoodsPara.getItemId().contains("http")) {//商品链接
                    simpleTurnLinkDto.setUrl(fdGoodsPara.getItemId());
                } else {
                    //先查找淘宝id
                    String itemId = Tools.findTbItemIdByRegex(fdGoodsPara.getItemId());
                    if (StringUtils.isNotBlank(itemId)) {
                        simpleTurnLinkDto.setItemId(fdGoodsPara.getItemId());
                    } else {
                        //查找淘口令，找到通过淘口令转链
                        String pwd = Tools.findTbPwdByRegex(fdGoodsPara.getItemId());
                        if (StringUtils.isNotBlank(pwd)) {
                            simpleTurnLinkDto.setPwd(pwd);
                        } else { //最后则默认为商品id
                            simpleTurnLinkDto.setItemId(fdGoodsPara.getItemId());
                        }
                    }
                }

                simpleTurnLinkDto.setTokenId(tbTokenId);
                simpleTurnLinkDto.setPid(tbPid);
                simpleTurnLinkDto.setRid(tbRid);
                uzaiRespVo = uzaiTurnlinkFeignService.tbTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用淘宝转链- 参数={}，返回结果={}", JSONObject.toJSONString(simpleTurnLinkDto), JSONObject.toJSONString(uzaiRespVo));
            }

        } else if (PlatformTypeEnum.PT_JD.getId().intValue() == fdGoodsPara.getPlatform().intValue()) { //京东

            if (jdTokenId == null) { //发单设备方案未配置京东联盟id
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置京东联盟");
            } else {

                //判断输入得是商品id还是商品链接
                if (fdGoodsPara.getItemId().contains("http")) {//商品链接
                    simpleTurnLinkDto.setUrl(fdGoodsPara.getItemId());
                } else {
                    simpleTurnLinkDto.setItemId(fdGoodsPara.getItemId());
                }

                simpleTurnLinkDto.setTokenId(jdTokenId);
                uzaiRespVo = uzaiTurnlinkFeignService.jdTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用京东转链- 参数={}，返回结果={}", JSONObject.toJSONString(simpleTurnLinkDto), JSONObject.toJSONString(uzaiRespVo));
            }

        } else if (PlatformTypeEnum.PT_PDD.getId().intValue() == fdGoodsPara.getPlatform().intValue()) { //拼多多

            if (pddTokenId == null) { //发单设备方案未配置拼多多联盟id
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置拼多多联盟");
            } else {

                //判断输入得是商品id还是商品链接
                if (fdGoodsPara.getItemId().contains("http")) {//商品链接
                    simpleTurnLinkDto.setUrl(fdGoodsPara.getItemId());
                } else {
                    simpleTurnLinkDto.setItemId(fdGoodsPara.getItemId());
                }

                simpleTurnLinkDto.setTokenId(pddTokenId);
                simpleTurnLinkDto.setPddTokenType(pddTokenType);
                simpleTurnLinkDto.setUseZsUnitUrl(true);
                uzaiRespVo = uzaiTurnlinkFeignService.pddTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用拼多多转链- 参数={}，返回结果={}", JSONObject.toJSONString(simpleTurnLinkDto), JSONObject.toJSONString(uzaiRespVo));
            }

        } else if (PlatformTypeEnum.PT_VPH.getId().intValue() == fdGoodsPara.getPlatform().intValue()) { //唯品会
            if (vphTokenId == null) { //发单设备方案未配置唯品会联盟id
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置唯品会联盟");
            } else {

                //判断输入得是商品id还是商品链接
                if (fdGoodsPara.getItemId().contains("http")) {//商品链接
                    simpleTurnLinkDto.setUrl(fdGoodsPara.getItemId());
                } else {
                    simpleTurnLinkDto.setItemId(fdGoodsPara.getItemId());
                }

                simpleTurnLinkDto.setTokenId(vphTokenId);
                uzaiRespVo = uzaiTurnlinkFeignService.vphTurnlinkSimple(simpleTurnLinkDto);
                logger.info("---调用唯品会转链- 参数={}，返回结果={}", JSONObject.toJSONString(simpleTurnLinkDto), JSONObject.toJSONString(uzaiRespVo));
            }
        } else if (fdGoodsPara.getPlatform().intValue() == 4) {  //抖音
            if (dyTokenId == null) { //发单设备方案未配置抖音联盟id
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "设备方案未配置抖音联盟");
            } else {
                simpleTurnLinkDto.setPwd(fdGoodsPara.getItemId());
                simpleTurnLinkDto.setTokenId(dyTokenId);
                simpleTurnLinkDto.setDyTokenType(dyTokenType);
                simpleTurnLinkDto.setUseZsUnitUrl(true);
                uzaiRespVo = uzaiTurnlinkFeignService.dyTurnlinkSimple(simpleTurnLinkDto);

                logger.info("---调用抖音转链- 参数={}，返回结果={}", JSONObject.toJSONString(simpleTurnLinkDto), JSONObject.toJSONString(uzaiRespVo));
            }
        }

        if (uzaiRespVo != null) {
            if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                simpleTurnlinkVo = uzaiRespVo.getData();
            } else {
                logger.error(JSONObject.toJSONString(new BizLog(LogBizTypeEnum.CONSOLE_FD_SEND_HANDER_VALUE,
                        simpleTurnLinkDto.getMerId(), device.getRecvmsgType(), device.getId(),
                        "", 0L,
                        "转链失败；" + uzaiRespVo.getMsg())));

                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
            }
        }

        return simpleTurnlinkVo;
    }


}
